package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.auth.mapper.IUserDao;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.*;
import com.koocloud.electroplatemanage.pojo.*;
import com.koocloud.electroplatemanage.pojo.mainpojo.OrderResource;
import com.koocloud.electroplatemanage.pojo.mainpojo.WIP;
import com.koocloud.electroplatemanage.service.ProductionTaskService;
import com.koocloud.electroplatemanage.utils.HexUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.IncomePartJudgeSqlFieldConstant.*;
import static com.koocloud.electroplatemanage.constant.MainWIPRouteConstant.*;

/**
 * @program: Information_platform
 * @description: 生产任务单实现层
 * @author: xxc
 * @create: 2020-11-05 14:55
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class ProductionTaskServiceImpl implements ProductionTaskService {
    @Resource
    ProductionTaskMapper productionTaskMapper;
    @Resource
    ProductionPlanMapper productionPlanMapper;
    @Resource
    private MainProductionMapper mainProductionMapper;
    @Resource
    IUserDao iUserDao;
    @Resource
    private DrawNoMapper drawNoMapper;
    @Resource
    private TypeWorkMapper typeWorkMapper;
    @Resource
    private ProductPlanUrgentMapper productPlanUrgentMapper;
    Lock lock = new ReentrantLock();
    @Override
    public ResponseTemplate selectAllData(String page,String limit,String beginTime,String endTime,ProductionTask productionTask) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                //开始分页
                PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                //如果不传就查询当天的
                if (StringUtils.isEmpty(beginTime)){
                    beginTime= HexUtil.getCurrentDate();
                }
                if (StringUtils.isEmpty(endTime)){
                    endTime=HexUtil.getCurrentDate();
                }

                List<ProductionTask> ProductionTaskList = productionTaskMapper.selectAllData(beginTime,endTime,productionTask);
                //构造分页实体
                PageInfo<ProductionTask> info=new PageInfo<>(ProductionTaskList);
                if (info.getTotal()>0) {
                    //查询到数据
                    return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                } else {
                    //没有查询到数据
                    return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }
        }
        else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }

    /**
     *@Description:  插入一条数据
     *@Param: [productionTask, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/19
     */
    @Override
    public ResponseTemplate insert(ProductionTask productionTask, String userId) {
        try {
            lock.lock();
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String strDate = df.format(date);//获取String类型的时间
            //设置创建时间
            productionTask.setCreateTime(strDate);
            productionTask.setDeleteFlag("1");
            //设置创建人
            User user = iUserDao.selectByPk(userId);
            productionTask.setCreator(user.getJobNum());
            int rows = 0;
            //根据工单号查看生产计划中是否有此工单，有 未拆分  无 拆分
            ProductionPlan productionPlan = productionPlanMapper.selectByWorkOrderNumber(productionTask.getWorkOrderNumber());
            ProductionPlan productionPlancheck = productionPlanMapper.selectByWorkOrderNumber(productionTask.getPlanWorkOrderNumber());
            if (!StringUtils.isEmpty(productionPlancheck)){
                if(Integer.parseInt(productionTask.getTaskQuantity())-Integer.parseInt(productionPlancheck.getCurrentQuantity())>0) {
                    return ResponseTemplate.builder().code(1).message("任务数量过大！请您减小！").count(1l).build();
                }
            }


            if (!StringUtils.isEmpty(productionPlan)){

                //有
                rows = productionTaskMapper.insert(productionTask);
            }else {
                //无  拆分的工单号  插入
                rows = productionTaskMapper.insert(productionTask);
                /*//查看拆分的字母 (目前工单号末尾为A 的为上级  其他全为子集)
                char[] letters = LETTER.toCharArray();
                char[] workOrderNum = productionTask.getWorkOrderNumber().toCharArray();
                for (int i = 0; i < letters.length ; i++){
                    if (letters[i] == workOrderNum[workOrderNum.length-1]){
                        workOrderNum[workOrderNum.length-1] = letters[i-1];
                        break;
                    }
                }
                String newWorkOrderNumber = new String(workOrderNum);*/
                //更改生产计划表数量
                ProductionPlan productionPlanSuper = productionPlanMapper.selectByWorkOrderNumber(productionTask.getPlanWorkOrderNumber());

                if (Integer.parseInt(productionPlanSuper.getCurrentQuantity())-Integer.parseInt(productionTask.getTaskQuantity())>0){
                    productionPlanSuper.setCurrentQuantity(String.valueOf(Integer.parseInt(productionPlanSuper.getCurrentQuantity())-Integer.parseInt(productionTask.getTaskQuantity())));
                }else {
                    productionPlanSuper.setCurrentQuantity(ZERO);
                    productionPlanSuper.setDeleteFlag(TWO);
                }
                productionPlanMapper.update(productionPlanSuper);

                //生产在工表
                //根据生产计划工单号进行查询
                WIP wip = mainProductionMapper.selectWIPByPk(productionTask.getPlanWorkOrderNumber());
                wip.setCurrentLocation(SCHEDULING);
                wip.setWorkOrderNumber(productionTask.getWorkOrderNumber());
                mainProductionMapper.insertWIP(wip);
                //生产实际表AVIC2020112105523A
                String postion = PROCESSPREPARATION;
                List<OrderResource> orderResourceList = mainProductionMapper.selectOrderResourceByworkOrderNumber(productionTask.getPlanWorkOrderNumber(),postion);
                if(!StringUtils.isEmpty(orderResourceList.get(0))) {
                    OrderResource orderResource = orderResourceList.get(0);
                    orderResource.setRoutePosition(SCHEDULING);
                    orderResource.setFatherId(orderResource.getId());
                    orderResource.setWorkOrderNumber(productionTask.getWorkOrderNumber());
                    mainProductionMapper.insertOrderResource(orderResource);

                }

            }

            if (rows > 0) {
                return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
            } else {//没有异常并且插入数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
            }

        } catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //出现异常返回异常原因
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    @Override
    public ResponseTemplate delete(String id, String userId) {

        try {
            lock.lock();
            ProductionTask productionTask = productionTaskMapper.selectById(id);
            if (!StringUtils.isEmpty(productionTask) && !StringUtils.isEmpty(productionTask.getProductionStartTime())){
                //获取当前日期
                Date currentDate = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateString=sdf.format(currentDate)+" 23:59:59";
                //当天结束日期时间
                Date dateEnd=sdf.parse(dateString);
                //开始时间
                Date productionTaskDate=sdf.parse(productionTask.getProductionStartTime());
                //判断要删除的数据是否为今天之后的数据
                if(productionTaskDate.getTime()<=dateEnd.getTime()){
                    return ResponseTemplate.builder().code(1).message("不能删除当天及之前的数据!").count(0l).build();
                }else {
                    //设置创建人
                    User user = iUserDao.selectByPk(userId);
                    int rows = productionTaskMapper.delete(id,user.getJobNum());
                    //判断删除操作是否成功
                    if (rows > 0) {
                        //删除成功返回数据
                        return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
                    }
                    else {
                        //删除失败返回提示
                        return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
                    }
                }
            }else {
                return ResponseTemplate.builder().code(1).message("请填入生产计划开始时间").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            //手动事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    @Override
    public ResponseTemplate update(ProductionTask productionTask, String userId) {
        try {
            lock.lock();
            if (!StringUtils.isEmpty(productionTask) && !StringUtils.isEmpty(productionTask.getProductionStartTime())){
                //获取当前日期
                Date currentDate = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String dateString=sdf.format(currentDate)+" 23:59:59";
                //当天结束日期时间
                Date dateEnd=sdf.parse(dateString);
                //开始时间
                Date productTaskDate=sdf.parse(productionTask.getProductionStartTime());
                //判断要修改的数据是否为今天之后的数据
                if(productTaskDate.getTime()<=dateEnd.getTime()) {
                    return ResponseTemplate.builder().code(1).message("不能修改当天及之前的数据!").count(0l).build();
                }else {
                    //设置创建人
                    User user = iUserDao.selectByPk(userId);
                    productionTask.setModifier(user.getJobNum());
                    //没有异常并且修改数据条数大于0
                    int rows = productionTaskMapper.update(productionTask);
                    if(rows>0) {
                        return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
                    }
                    else {//没有异常并且修改数据失败，原则上不出现
                        return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
                    }
                }
            }else {
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 判断当前任务单是否需要拆分
     *@Param: [workOrderNumber, taskQuantity]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/19
     */
    @Override
    public ResponseTemplate inspectTasksNum(String workOrderNumber, String taskQuantity) {
        try{
            if(!StringUtils.isEmpty(workOrderNumber)&&!StringUtils.isEmpty(taskQuantity)&&Validator.isNumber(taskQuantity)) {

                //根据工单号查询此工单号的当前单据数量
                ProductionPlan productionPlan = productionPlanMapper.selectByWorkOrderNumber(workOrderNumber);
                if (Integer.parseInt(taskQuantity) > 0 && Integer.parseInt(taskQuantity) < Integer.parseInt(productionPlan.getCurrentQuantity())) {
                    char[] letters = LETTER.toCharArray();
                    char[] workOrderNum = workOrderNumber.toCharArray();
                    for (int i = 0; i < letters.length; i++) {
                        if (letters[i] == workOrderNum[workOrderNum.length - 1]) {
                            workOrderNum[workOrderNum.length - 1] = letters[i + 1];
                            break;
                        }
                    }
                    String newWorkOrderNumber = new String(workOrderNum);
                    while (true) {
                        ProductionTask productionTask = productionTaskMapper.selectByWorkOrderNumber(newWorkOrderNumber);
                        if (!StringUtils.isEmpty(productionTask)) {
                            workOrderNum = newWorkOrderNumber.toCharArray();
                            for (int i = 0; i < letters.length; i++) {
                                if (letters[i] == workOrderNum[workOrderNum.length - 1]) {
                                    workOrderNum[workOrderNum.length - 1] = letters[i + 1];
                                    break;
                                }
                            }
                            newWorkOrderNumber = new String(workOrderNum);
                        } else {
                            break;
                        }
                    }
                    LinkedHashMap linkedHashMap = new LinkedHashMap();
                    linkedHashMap.put("workOrderNumber", newWorkOrderNumber);
                    return ResponseTemplate.builder().code(0).message("拆分成功").data(linkedHashMap).count(0l).build();
                } else if (Integer.parseInt(taskQuantity) == Integer.parseInt(productionPlan.getCurrentQuantity())) {
                    LinkedHashMap linkedHashMap = new LinkedHashMap();
                    linkedHashMap.put("workOrderNumber", workOrderNumber);
                    return ResponseTemplate.builder().code(0).message("无需拆分").data(linkedHashMap).count(0l).build();
                } else {
                    return ResponseTemplate.builder().code(1).message("任务数量输入异常！请重新输入").count(0l).build();
                }
            }
            else {
                return ResponseTemplate.builder().code(1).message("参数为空或者任务数量非数值型").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *@Description: 任务单确认按钮
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/19
     */
    @Override
    public ResponseTemplate confirmEntryInfo(String workOrderNumber, String uesrId) {
        try{
            lock.lock();
            //操作人
            User user = iUserDao.selectByPk(uesrId);
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String strDate = df.format(date);//获取String类型的时间
            //改变任务单状态
            productionTaskMapper.changeState(workOrderNumber);
            /*//工单号表
            WorkOrder workOrder = mainProductionMapper.selectWorkOrderByPk(workOrderNumber);
            workOrder.setCurrentLocation(PROCESSPREPARATION);
            int limit = mainProductionMapper.updateWorkOrder(workOrder);*/
            //生产在工表
            WIP wip = mainProductionMapper.selectWIPByPk(workOrderNumber);
            wip.setCurrentLocation(PRODUCTION);
            int rows =  mainProductionMapper.updateWIP(wip);
            //生产实际表
            String postion = SCHEDULING;
            List<OrderResource> orderResourceList = mainProductionMapper.selectOrderResourceByworkOrderNumber(workOrderNumber,postion);
            int row = 0;
            if(!StringUtils.isEmpty(orderResourceList.get(0))) {
                OrderResource orderResource = orderResourceList.get(0);
                //上一状态完成时间
                orderResource.setCompletionTime(strDate);
                //上一状态完成人
                orderResource.setCompletedPerson(user.getJobNum());
                mainProductionMapper.updateOrderResource(orderResource);
                orderResource.setRoutePosition(PRODUCTION);
                //投入时间
                orderResource.setEntryTime(strDate);
                //投入人
                orderResource.setEntryPerson(user.getJobNum());
                //上一状态完成时间
                orderResource.setCompletionTime(null);
                //上一状态完成人
                orderResource.setCompletedPerson(null);
                row = mainProductionMapper.insertOrderResource(orderResource);

            }
            if(rows>0 && row >0) {
                return ResponseTemplate.builder().code(0).message("确认成功").count(1l).build();
            } else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("确认失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }

    }

    /**
     *@Description:生产计划工单号查询数据(生产计划或生产计划加急点击任务单按钮时跳任务单新增时调用)
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: zww
     *@date: 2020/11/19
     */
    @Override
    public ResponseTemplate selectDataByWorkOrderNumber(ProductionTask productionTaskFe) {
        try{
            //新建生产计划实体
            ProductionPlan productionPlan = null;
            productionPlan = productionPlanMapper.selectById(productionTaskFe.getWorkOrderNumber());
            //判断查表操作是否成功
            if (null != productionPlan) {
                ProductionTask productionTask = new ProductionTask();
                if(!StringUtils.isEmpty(productionPlan.getWorkOrderNumber())) {
                    //设置工单号
                    productionTask.setWorkOrderNumber(productionPlan.getWorkOrderNumber());
                }
                if(!StringUtils.isEmpty(productionPlan.getState())) {
                    //设置状态
                    productionTask.setWorkOrderNumber(productionPlan.getState());
                }
                if(!StringUtils.isEmpty(productionPlan.getOrderNumber())) {
                    //设置订单号
                    productionTask.setOrderNumber(productionPlan.getOrderNumber());
                }
                if(!StringUtils.isEmpty(productionPlan.getDrawNoCode())) {
                    //设置图号编码
                    productionTask.setDrawNoCode(productionPlan.getDrawNoCode());
                    DrawNoVo drawNoVo = drawNoMapper.selectByPk(productionPlan.getDrawNoCode());
                    if (!StringUtils.isEmpty(drawNoVo)) {
                        if(!StringUtils.isEmpty(drawNoVo.getName())) {
                            //设置图号名称
                            productionTask.setDrawNoName(drawNoVo.getName());
                        }
                    }
                }
                if(!StringUtils.isEmpty(productionPlan.getModelNumber())) {
                    //设置型号
                    productionTask.setModelNumber(productionPlan.getModelNumber());
                }
                if(!StringUtils.isEmpty(productionPlan.getModelType())) {
                    //设置型别
                    productionTask.setModelType(productionPlan.getModelType());
                }
                if(!StringUtils.isEmpty(productionPlan.getPartName())) {
                    //设置零件名称
                    productionTask.setPartName(productionPlan.getPartName());
                }
                if(!StringUtils.isEmpty(productionPlan.getLine())) {
                    //设置线路
                    productionTask.setLine(productionPlan.getLine());
                }
                if(!StringUtils.isEmpty(productionPlan.getTypeWorkCode())) {
                    //设置工种编码
                    productionTask.setTypeWorkCode(productionPlan.getTypeWorkCode());
                    TypeWorkVo typeWorkVo = typeWorkMapper.selectByPk(productionPlan.getTypeWorkCode());
                    if (!StringUtils.isEmpty(typeWorkVo)) {
                        if(!StringUtils.isEmpty(typeWorkVo.getName())) {
                            //设置工种名称
                            productionTask.setTypeWorkName(typeWorkVo.getName());
                        }

                    }
                }
                if(!StringUtils.isEmpty(productionPlan.getWorkOrderNumber())) {
                    //设置生产计划工单号
                    productionTask.setPlanWorkOrderNumber(productionPlan.getWorkOrderNumber());
                }
                if(!StringUtils.isEmpty(productionTaskFe.getHtmlCode())) {
                    //已完成0，暂未进行1，加急2，二次加急3，进行中4
                    if("0".equals(productionTaskFe.getHtmlCode())) {//未加急
                        productionTask.setState("1");
                    }
                    if("1".equals(productionTaskFe.getHtmlCode())) {//加急
                        productionTask.setState("2");
                        //判断是否二次加急
                        String order = productPlanUrgentMapper.selectOrderByProductionPlanId(productionPlan.getWorkOrderNumber());
                        if("-999".equals(order)) {
                            //二次加急
                            productionTask.setState("3");
                        }
                    }
                }
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(productionTask).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        }
        catch (Exception e) {
            //事务手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

}
